<?php

namespace App\Http\BizServices;

use App\Http\Request\ClickRequest;
use App\Http\Request\DownloadRequest;
use App\Http\Request\ExposureRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class ReportBizService extends BaseService
{
    public function exposure(ExposureRequest $request)
    {
        $adId    = DB::table('advertisements')->where('ad_id', $request->adId)->value('id');
        $insertId = DB::table('ad_exposures')->insertGetId([
            'user_id' => $this->getUserId(),
            'ad_id' => $adId,
            'exposure_time' => $request->second,
            'placement' => $request->location,
            'start_time' => $request->startTime,
            'end_time' => $request->endTime,
        ]);
        return $insertId;
    }

    public function click(ClickRequest $request)
    {
        $adId    = DB::table('advertisements')->where('ad_id', $request->adId)->value('id');
        $insertId = DB::table('ad_clicks')->insertGetId([
            'user_id' => $this->getUserId(),
            'ad_id' => $adId,
            'click_type' => $request->clickType,
        ]);
        return $insertId;
    }

    public function download(DownloadRequest $request)
    {

    }

    private function getUserId()
    {
        $deviceId = Session::get('deviceId');
        $user = DB::table('users')->where('device_id', $deviceId)->first();
        if ($user) {
            return $user->id;
        }
        DB::table('users')->insert([
            'device_id' => $deviceId,
            'ip' => request()->ip(),
            'uuid' => request()->header('x-uuid'),
            'imei' => request()->header('x-imei'),
            'system_version' => request()->header('x-system-version')
        ]);
    }
}
